"""Site override, stored in Cinema 4D's world plugin data.

`GetWorldPluginData`/`SetWorldPluginData` persist a BaseContainer in C4D's own
preferences — the mirror of Blender's AddonPreferences, and for the same reason:
a URL is not a secret, so it may live in preferences, while the credential never
does (it stays in ~/.three-blocks/credentials.json, shared with the CLI).
"""

from __future__ import annotations

import os

import c4d

from ._core import config

HUB_ID = 1000001  # dev-range id; swap for the Plugin Café block before release
TOOL_DIALOG_ID_BASE = 1000002  # hub-assigned tool sub-dialog ids (dev range too)
SITE_OVERRIDE = 1000  # BaseContainer key inside our world data
BRIDGE_AUTOSTART = 1001  # remember the live-bridge toggle across launches


def site_override() -> str:
    container = c4d.plugins.GetWorldPluginData(HUB_ID)
    if not container:
        return ""
    return str(container.GetString(SITE_OVERRIDE) or "").strip()


def set_site_override(value: str) -> None:
    container = c4d.plugins.GetWorldPluginData(HUB_ID) or c4d.BaseContainer()
    container.SetString(SITE_OVERRIDE, (value or "").strip())
    c4d.plugins.SetWorldPluginData(HUB_ID, container)


def bridge_autostart() -> bool:
    """Whether the live bridge re-arms itself on the next launch."""
    container = c4d.plugins.GetWorldPluginData(HUB_ID)
    if not container:
        return False
    return str(container.GetString(BRIDGE_AUTOSTART) or "") == "1"


def set_bridge_autostart(value: bool) -> None:
    container = c4d.plugins.GetWorldPluginData(HUB_ID) or c4d.BaseContainer()
    container.SetString(BRIDGE_AUTOSTART, "1" if value else "")
    c4d.plugins.SetWorldPluginData(HUB_ID, container)


def effective_site_url() -> str:
    env = os.environ.get("TB_SITE_URL")
    if env:
        return env.rstrip("/")
    override = site_override()
    if override:
        return override.rstrip("/")
    return config.DEFAULT_SITE
